﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Drawing;
using Silvermoon.OpenGL.Native;
using System.Drawing.Imaging;

namespace Silvermoon.OpenGL
{
    /// <summary>
    /// Canvas to paint on a <see cref="Texture"/>.
    /// </summary>
    public class DrawingCanvas : IDisposable
    {
        private Texture texture;
        internal Bitmap bitmap;
        private TextureFormat format;
        private Color transparentColor;
        private Graphics graphics;
        private Size Size;

        internal DrawingCanvas(Texture texture, int width, int height, TextureFormat format, Color transparentColor)
        {
            this.texture = texture;
            this.bitmap = CreateBitmap(width, height, format);
            this.format = format;
            this.transparentColor = transparentColor;
        }

        /// <summary>
        /// Gets the Graphics for rendering.
        /// </summary>
        public Graphics Graphics
        {
            get
            {
                if (graphics == null) graphics = Graphics.FromImage(bitmap);
                return graphics;
            }
        }

        /// <summary>
        /// Releases all resources and updates the graphics to the texture.
        /// </summary>
        public void Dispose()
        {
            DiposeAll(true);
            GC.SuppressFinalize(this);
        }

        ~DrawingCanvas()
        {
            DiposeAll(false);
        }


        private void DiposeAll(bool update)
        {
            if (graphics != null) graphics.Dispose();
            graphics = null;
            if (update) UpdateTexture();
            texture = null;
            if (bitmap != null) bitmap.Dispose();
            bitmap = null;
        }



        private Bitmap CreateBitmap(int width, int height, TextureFormat format)
        {
            int bmWidth = TextureUtil.ConvertToValidTextureDimension(width);
            int bmHeight = TextureUtil.ConvertToValidTextureDimension(height);

            PixelFormat pFormat = TextureUtil.GetPixelFormatFromTextureFormat(format);
            Bitmap bm = new Bitmap(bmWidth, bmHeight, pFormat);

            this.Size = new Size(width, height);
            return bm;
        }

        /// <summary>
        /// Updates the texture with the image from the graphics.
        /// </summary>
        public void UpdateTexture()
        {
            texture.CopyBitmap(bitmap, format, transparentColor, Size);
        }
    }
}
